#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>

using namespace std;

class Solution {
public:

    //873. 最长的斐波那契子序列的长度
    // https://leetcode.cn/problems/length-of-longest-fibonacci-subsequence/
    int lenLongestFibSubseq(vector<int>& arr) {
        unordered_map<int, int> hash;
        int n = arr.size();
        vector<vector<int>> dp(n, vector<int>(n, 2));

        for (int i = 0; i<n; ++i)
            hash[arr[i]] = i;

        int ans = 2;
        for (int i = 1; i<n; ++i)
        {
            for (int j = i+1; j<n; ++j)
            {
                int a = arr[j] - arr[i];
                if (hash.count(a) && a<arr[i])
                    dp[i][j] = dp[hash[a]][i] + 1;
                ans = max(ans, dp[i][j]);
            }
        }

        return ans < 3 ? 0 : ans;
    }

    // 1027. 最长等差数列
    // https://leetcode.cn/problems/longest-arithmetic-subsequence/
    int longestArithSeqLength(vector<int>& nums) {
        int n = nums.size();
        unordered_map<int, int> hash;
        vector<vector<int>> dp(n, vector<int>(n, 2));
        hash[nums[0]] = 0;

        int ans = 2;
        for (int i = 1; i<n; ++i)
        {
            for (int j = i+1; j<n; ++j)
            {
                int a = 2 * nums[i] - nums[j];
                if (hash.count(a))
                    dp[i][j] = dp[hash[a]][i] + 1;
                ans = max(ans, dp[i][j]);
            }
            hash[nums[i]] = i;
        }

        return ans;
    }
};